import Taro from '@tarojs/taro'
import {showInfo} from "../utils/ToastUtils";
import LogService from "./LogService";
import {ab2hex} from "../utils/CommonUtils";

export default class BleDeviceService {

  /**
   * 打开蓝牙
   * @returns {Promise<unknown>}
   */
  static openBlu() {

    let promise = new Promise(function (resolve, reject) {
      Taro.openBluetoothAdapter({
        success: function (res) {
          LogService.debug("openBluetoothAdapter success", res)
          resolve(res);
        },
        fail: function (res) {
          LogService.error("openBluetoothAdapter fail", res);
          showInfo("请打开手机蓝牙");
          reject(res);
        }
      })
    });
    return promise;

  }

  /**
   * 扫描设备
   * @returns {Promise<void>}
   */
  static async scan() {
    if (!await BleDeviceService.isAvaible()) {
      showInfo("请打开手机蓝牙");
      return false;
    }

    await BleDeviceService.stopSCan();
    LogService.debug("start scan");

    // 以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
    Taro.startBluetoothDevicesDiscovery({
      // services: [APPConfig.Service_UUID],
      success: function (res1) {
        LogService.info("startBluetoothDevicesDiscovery", res1)
      }
    })

    return true;

  }

  /**
   * RSSI: -83
   advertisData: ArrayBuffer(9)
   [[Int8Array]]: Int8Array(9) [76, 0, 16, 5, 69, 28, 123, 32, -23]
   [[Uint8Array]]: Uint8Array(9) [76, 0, 16, 5, 69, 28, 123, 32, 233]
   advertisServiceUUIDs: []
   connectable: true
   deviceId: "60:DE:8A:DC:3A:31"
   localName: "alibaba-inc"
   name: "alibaba-inc"
   */
  static getBluetoothDevices(name, callback) {
    Taro.getBluetoothDevices({
      success: function (res) {
        var devices = res.devices;
        if (!devices || devices.size == 0)
          return;
        if (!!name)
          devices = devices.filter(value => value.name == name);
        !!callback && callback(devices);
        devices.forEach(device => {
          LogService.info(device, ab2hex(device.advertisData))
        })
      }
    })
  }

  static async stopSCan() {

    if (!await BleDeviceService.isAvaible()) {
      showInfo("请打开手机蓝牙");
      return;
    }

    const res = await Taro.stopBluetoothDevicesDiscovery();
    LogService.info("stopBluetoothDevicesDiscovery", res);
  }

  static async isAvaible() {
    try {
      const res = await BleDeviceService.getBluState();
      const {available} = res;
      return available;
    } catch (e) {
      return false;
    }
  }

  static async isDiscovering() {
    try {
      const res = await BleDeviceService.getBluState();
      const {discovering} = res;
      return discovering ? 1 : 0;
    } catch (e) {
      return -1;
    }
  }

  /**
   * available  boolean  蓝牙适配器是否可用
   discovering  boolean  是否正在搜索设备
   errMsg  string  成功：ok，错误：详细信息
   */
  static getBluState() {
    let promise = new Promise(function (resolve, reject) {
      Taro.getBluetoothAdapterState({
        success: function (res) {
          LogService.info("getBluetoothAdapterState success", res);
          resolve(res);
        },
        fail: function (res) {
          LogService.info("getBluetoothAdapterState fail", res);
          reject(res);
        },
      })
    });
    return promise;
  }

}

